<template>
    <div class='detail'>
        <van-nav-bar
            title="详情"
            left-text="返回"
            left-arrow
            @click-left="onClickLeft"
        />
        <van-card
            num="1"
            :price="obj.price"
            :desc="obj.descriptions"
            :title="obj.name"
            :thumb="obj.coverImg"
        />
        <van-button type="info" block @click="addcart(obj._id)"
        >添加购物车</van-button
        >
    </div>
</template>

<script>
import { reqProductDetail } from "../../api/products";
import { addToCart } from "../../api/cart";
import { Toast } from "vant";
export default {
    
    components: {},
    data() {
        
        return {
            id: "",
            obj: [],
        };
    },
    computed: {},
    watch: {},
    
    methods: {
        onClickLeft() {
            this.$router.push("/home")
        },
        //   初始化详情
        async init(id){
            const result = await reqProductDetail(id);
            console.log(result);
            this.obj = result.data;
        },
        // 添加购物车
        async addcart(id) {
            // id表示商品的id
            const result = await addToCart(id);
            console.log(result);
            if (result.data.code === "success") {
                Toast.success("添加购物车成功");
                this.$router.push("/cart");
            }
        },
    },
    created() {
        // 接受路由传过来的参数
        // alert(this.$route.query.id) //刷新页面 参数没有丢失
        // alert(this.$route.params.id) //   params传参  params传参刷新页面参数丢失
        // alert(this.$route.params.id) // 接受动态路由参数 刷新页面不会丢失
        this.id = this.$route.params.id;
        this.init(this.id)
    },
    mounted() {
        
    },
    }
</script>
<style scoped>
    
</style>